package com.cvtt.core;

import java.util.HashMap;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;

import com.cvtt.common.AlarmUtil;
import com.cvtt.common.NetworkUtil;
import com.cvtt.sip.SIPEngine;
import com.cvtt.sip.SIPListener;
import com.voipAgent.SipAgent;
import com.voipAgent.SipAgent.SipEventListener;

public class SIPCore extends CoreEventHandler implements SIPListener {

	private static final String LOG_TAG = "SIPCore";

	private Application uApp;

	private SIPEngine sipEngine;

	private Context context;

	private boolean bShowRedirect;

	private int RETRY_TIME = 180;
	private boolean bSIPLoginFlag = true;

	private static SIPCore sipCore = null;
	private String userName="";
	private String userPassword ="";
	public static boolean bExit;
	private SipEventListener sipEventListener;
	public static final String SIP_USER_NAME = "sip_user_name";
	public static final String SIP_USER_PASSWORD = "sip_user_password";
	public static final String SIP_MASTER_SERVER = "sip_master_server";
	public static final String SIP_MASTER_SERVERDOMAIN = "sip_master_domain";
	public static final String SIP_MASTER_SERVERPORT = "sip_master_port";

	private static final String TAG = "SIPCore";
	public static synchronized SIPCore getInstance(Context context,SipEventListener eventListener) {
		if (sipCore == null) {
			sipCore = new SIPCore(context,eventListener);
		}
		return sipCore;
	}

	public static SIPCore getSIPCore() {
		return sipCore;
	}

	private SIPCore(Context context,SipEventListener eventListener) {
		sipEngine = SIPEngine.getInstance(context, this);
		sipEventListener=eventListener;
		this.context = context;
	}

	public boolean isOnline() {
		sipEventListener.isSipOnline(sipEngine.isOnline());
		return sipEngine.isOnline();
	}



	public void pwLock(boolean lock) {
//		pwLockManager.cpuWakeLock(lock);
	}

	public void keepAlive() {
		pwLock(true);
		if (!NetworkUtil.isAvailable(context)) {
			postCoreEvent(SipAgent.U_AWAY, null);
		}
		else {
			postCoreEvent(SipAgent.U_SIP_KEEP_ALIVE, null);
		}
	}

	@Override
	public void handleCoreEvent(int event, Object data) {
		
		
		switch (event) {			
			case SipAgent.U_START:
				/*if (NetworkUtil.isAvailable() && PreferencesUtil.hasUserInfo()) {
					sipEngine.start(PreferencesUtil.getUserNumber(), PreferencesUtil.getUserPasswordMD5());
					UUtil.writeLog("sip -------------start-----------");
				}*/
			/*	HashMap<String, String> hashMap = (HashMap<String, String>) data;
				String sipServer = hashMap.get(SIPCore.SIP_MASTER_SERVER);
				String sipDomain = hashMap.get(SIPCore.SIP_MASTER_SERVERDOMAIN);
				String sipPort = hashMap.get(SIPCore.SIP_MASTER_SERVERPORT);
				int port = Integer.parseInt(sipPort);*/
				HashMap<String, String> hashMap = (HashMap<String, String>) data;
//				ULogger.i(LOG_TAG, "sip login");
				if(data!=null){
					
					if(TextUtils.isEmpty(userName)){
						userName = hashMap.get(SIP_USER_NAME);
					}
					if(TextUtils.isEmpty(userPassword)){
						userPassword = hashMap.get(SIP_USER_PASSWORD);
					}
				}
				sipEngine.start(userName,userPassword);
				break;
			case SipAgent.U_SIP_LOGIN: {
				HashMap<String, String> hashMap1 = (HashMap<String, String>) data;
//				ULogger.i(LOG_TAG, "sip login");
				if(TextUtils.isEmpty(userName)){
					userName = hashMap1.get(SIP_USER_NAME);
				}
				if(TextUtils.isEmpty(userPassword)){
					userPassword = hashMap1.get(SIP_USER_PASSWORD);
				}
				sipEngine.setLoginInfo(userName, userPassword);
				sipEngine.register();
				if (NetworkUtil.isAvailable(context)) {
					pwLock(true);
					if (!sipEngine.register()) {
						pwLock(false);
//						ULogger.v(LOG_TAG, "sip register fail");
					}
					else {
//						ULogger.v(LOG_TAG, "sip register success");
						// UUtil.writeLog("sip register success");
					}
				}
				else {
					runTimer(RETRY_TIME);
				}
			}
				break;
			case SipAgent.U_SIP_KEEP_ALIVE: {
				if (sipEngine.register() == false)
					pwLock(false);
			}
				break;
			case SipAgent.U_STOP: 
				runTimer(0);
				sipEngine.stop();

			
				break;
			case SipAgent.U_RELOGIN: 
//				sipEngine.setLoginInfo(userName, userPassword);
				sipEngine.setLoginInfo(userName, userPassword);
			case SipAgent.U_RESTART:
				if (NetworkUtil.isAvailable(context)) {
						if (sipEngine.reStart() == false) {
							pwLock(false);
						}
				}
				else {
					postCoreEvent(SipAgent.U_RELOGIN, null, RETRY_TIME * 1000);
				}
				break;
			case SipAgent.U_LOGOUT: 
				runTimer(0);
				sipEngine.stop();
			
				break;
			case SipAgent.U_KICK: 
				sipEventListener.onSipKick();
				runTimer(0);
				sipEngine.stop();
			
				break;
			case SipAgent.U_AWAY: 
					sipEngine.stop();
//					uCore.updateStatus();// add by xiaofei 2014-2-11
//					sipEventListener.onSipUpdateStatus();
					runTimer(RETRY_TIME);
					pwLock(false);
			
				break;
	
			case SipAgent.U_CALL_OUT: 
				String number = (String) data;
				sipEngine.call(number);
				break;
			case SipAgent.U_CALL_OK: 
				sipEngine.answerCall();
			
				break;
			case SipAgent.U_END_CALL: 
				sipEngine.endCall(false);
				break;
			case SipAgent.U_CHECK_AND_END_CALL:
				sipEngine.checkAndEndCall();
				break;
			case SipAgent.U_SEND_DTMF:
				
				String key = (String) data;
				sipEngine.sendDTMF(key.charAt(0));
			
				break;
			case SipAgent.U_EXIT:
				onExit();
				break;
				
			case SipAgent.U_ENTER_BACKGROUND: {
				Log.i(LOG_TAG, "sip ----------------enter background----------------------");
				runTimer(0);
				sipEngine.stop();
			}
				break;
			case SipAgent.U_ENTER_FOREGROUND:
				Log.i(LOG_TAG,"sip -------------------enter foreground-------------------");
				if (NetworkUtil.isAvailable(context)) {
					pwLock(true);
					if (sipEngine.register() == false)
						pwLock(false);
				}
				else {
					runTimer(RETRY_TIME);
				}
				break;
			default:
				break;
		}
	}

	@Override
	public void onRegisterOK() {
		// TODO Auto-generated method stub
		sipEventListener.onSipLoginSuccess();
		sipEventListener.isSipOnline(true);
		pwLock(false);
	}

	@Override
	public void onRegisterError(int code) {
		// TODO Auto-generated method stub
		sipEventListener.onSipLoginError(code);
		sipEventListener.isSipOnline(false);
		pwLock(false);
	}

	@Override
	public void onRegisterEvent(int code) {
		// TODO Auto-generated method stub
		if (code == 200)
//			notifySIPEvent(SipAgent.U_LOGIN_SUCCESS);
			sipEventListener.onSipLoginSuccess();
		else
			sipEventListener.onSipLoginError(code);
		sipEventListener.onSipUpdateStatus();
		pwLock(false);
	}

	@Override
	public void onCallIn(String number) {
		// TODO Auto-generated method stub
		if (TextUtils.isEmpty(number))
			return;
		Log.i(TAG, "call in");
		Intent ceIntent = new Intent(SipAgent.ACTION_CALL_IN);
		ceIntent.putExtra(SipAgent.EXTRA_CALL_NUMBER, number);
		context.sendOrderedBroadcast(ceIntent, null);
	}

	@Override
	public void onCallRing() {
		// TODO Auto-generated method stub
		sipEventListener.onSipCallRing();
	}

	@Override
	public void onCallOK() {
		// TODO Auto-generated method stub
		sipEventListener.onSipCallOK();
	}

	@Override
	public void onCallEnd(int code) {
		// TODO Auto-generated method stub
		sipEventListener.onSipCallEnd(code);
	}

	@Override
	public void onCallEvent(int code) {
		// TODO Auto-generated method stub
		if (code == 200)
			sipEventListener.onSipCallOK();
		else if (code == 180 || code == 183)
			sipEventListener.onSipCallRing();
		else
			sipEventListener.onSipCallEnd(code);

	}

	@Override
	public void onSIPEvent(int code) {
		// TODO Auto-generated method stub
		Log.i(TAG, "onSIPEvent");
//		uCore.updateStatus();
		if (code == SIPEngine.STATUS_KICK) {
			sipEventListener.onSipKick();
//			uCore.postCoreEvent(UCore.U_KICK, null);
//			uCore.notifyUIEvent(UCore.U_KICK, null);
		}
		
	}

	public synchronized void runTimer(int time) {
		AlarmUtil.alarm(context, time, SIPTimerReceiver.class);
	}

	@Override
	public void onKeepAlive(int afterTime) {
		// TODO Auto-generated method stub
		runTimer(afterTime);
	}

	@Override
	public boolean isExited() {
		// TODO Auto-generated method stub
		return bExit;
	}

	@Override
	public void onExit() {
		super.onExit();
		runTimer(0);
		sipEngine.stop();
		bExit = true;
	}
	public SIPEngine getengine(){
		return sipEngine;
	}
}
